import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';
import { t } from '@lingui/macro';

export default class CompanyStore {
  _args = {
    search: {},
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  data = [];
  modal = [];
  companiesNames = [];
  loading = false;

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      this.data = yield api.search({ search, pg });
    } finally {
      this.loading = false;
    }
  }

  * getDriver(args) {
    return yield api.getDriver(args);
  }

  * create(args, data) {
    yield api.create(args, data);
    yield this.query();
  }

  * update(args, data) {
    yield api.update(args, data);
    yield this.query();
  }

  * get(id) {
    return yield api.get(id);
  }

  * validationPhone(args) {
    return yield api.validationPhone(args);
  }

  * getDicts(id) {
    const res = yield api.getDicts(id);
    return res.map((p) => ({ label: p.name, value: p.itemId }));
  }

  memberIdx(i, page, size) {
    return page * size + i + 1;
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }

  get api() {
    return api;
  }


  assembleData(members, vehicles) {
    const temp = members.reduce((acc, arr) => {
      const obj = {
        name: arr,
        saveVehicle: false,
      };
      if (vehicles.some((p) => p === arr)) {
        obj.saveVehicle = true;
      }
      acc.push(obj);
      return acc;
    }, []);
    return temp;
  }

  separateData(data) {
    const members = data.map((p) => p.name);
    const vehicles = data.filter((p) => p.saveVehicle).map((p) => p.name);
    return { members, vehicles };
  }
}
